#include "GraphicEngine.h"

GraphicEngine* GraphicEngine::m_Instance = NULL;

GraphicEngine::GraphicEngine(void)
{
	m_CameraPos.X = 0;
	m_CameraPos.Y = 0;
}

GraphicEngine::~GraphicEngine(void)
{
}

//region Properties
GraphicEngine* GraphicEngine::GetInstance()
{
	if(m_Instance == NULL)
	{
		m_Instance = new GraphicEngine();
	}
	return m_Instance;
}

SDL_Surface* GraphicEngine::GetMainScreen()
{
	return m_MainScreen;
}
// End of Properties

void GraphicEngine::SetMainScreen(SDL_Surface* screen)
{
	m_MainScreen = screen;
}

bool GraphicEngine::init(void)
{
	if( SDL_Init(SDL_INIT_VIDEO) <0 )
	{
	  //printf("Unable to init SDL: %s\n", SDL_GetError());
	  return false;
	}
	else
	{
		SDL_Surface* screen = NULL;
		screen = SDL_SetVideoMode(ScreenSizeX,ScreenSizeY,32,SDL_HWSURFACE|SDL_DOUBLEBUF);
		GraphicEngine::GetInstance()->SetMainScreen(screen);
	}
	return true;
}


void GraphicEngine::Slock(SDL_Surface *screen)
{
  if ( SDL_MUSTLOCK(screen) )
  {
	if ( SDL_LockSurface(screen) < 0 )
	{
	  return;
	}
  }
}

void GraphicEngine::Sulock(SDL_Surface *screen)
{
  if ( SDL_MUSTLOCK(screen) )
  {
	SDL_UnlockSurface(screen);
  }
}

void GraphicEngine::DrawTerrain(SDL_Surface* terrain)
{
	SDL_Surface* screen = GraphicEngine::GetInstance()->GetMainScreen();

	//TODO - Remove the Slock,Sulock and SDL_FLIP from here.. it's only for debugging
	GraphicEngine::GetInstance()->Slock(screen);
	GraphicEngine::GetInstance()->DrawIMG(terrain,MAIN_MAP_POSITION_X,MAIN_MAP_POSITION_Y,MAIN_MAP_SIZE_X,MAIN_MAP_SIZE_Y,m_CameraPos.X,m_CameraPos.Y);
	GraphicEngine::GetInstance()->Sulock(screen);
	SDL_Flip(screen);
}

// Blit an image on the screen surface
void GraphicEngine::DrawIMG(SDL_Surface *img, int x, int y)
{
	SDL_Surface* screen = GraphicEngine::GetInstance()->GetMainScreen();
	
	//GraphicEngine::GetInstance()->Slock(screen);
	SDL_Rect dest;
	dest.x = x;
	dest.y = y;
	SDL_BlitSurface(img, NULL, screen, &dest);
	//GraphicEngine::GetInstance()->Sulock(screen);
	//SDL_Flip(screen);	
}

// Blit a portion of an image on the screen surface
void GraphicEngine::DrawIMG(SDL_Surface *img, int x, int y, int w, int h, int x2, int y2)
{
	SDL_Surface* screen = GraphicEngine::GetInstance()->GetMainScreen();
	SDL_Rect dest;
	dest.x = x;
	dest.y = y;
	SDL_Rect dest2;
	dest2.x = x2;
	dest2.y = y2;
	dest2.w = w;
	dest2.h = h;
	SDL_BlitSurface(img, &dest2, screen, &dest);
}

SDL_Surface* GraphicEngine::ImageLoad(char *file)
{
  SDL_Surface *temp1;
  temp1 = SDL_LoadBMP(file);
 // SDL_FreeSurface(temp1);
  return temp1;
}